package yxy.game.pm2.command.tower;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.tower.TowerHandle;

/** 修炼塔 挑战执行 */
@MessageType(proto = Command.TowerChanllengeExecute, classtype = TowerMessage.TowerChanllengeExecuteRequest.class)
public class CMD_TowerChanllengeExecute extends Command<TowerMessage.TowerChanllengeExecuteRequest> {

	@Override
	public void execute(MessageSource messageSource, TowerMessage.TowerChanllengeExecuteRequest request) {
		String playerCode = messageSource.getTag();
		BattleMessage.BattleExecuteRequest battleReq = request.getBattleReq();

		TowerMessage.TowerChanllengeExecuteResponse.Builder response = TowerMessage.TowerChanllengeExecuteResponse.newBuilder();

		TowerHandle handle = new TowerHandle();
		if (handle.isBattling(playerCode)) {
			send(messageSource, response, Result.BattleIsRunning);// 之前的战斗未结束
			return;
		}

		try {
			response.setBattleResp(handle.battleResponseExecute(playerCode, battleReq));
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, TowerMessage.TowerChanllengeExecuteResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}